package cn.ito.zjgsu.realm;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.ito.zjgsu.domain.Role;
import cn.ito.zjgsu.domain.RoleExample;
import cn.ito.zjgsu.domain.User;
import cn.ito.zjgsu.domain.UserExample;
import cn.ito.zjgsu.service.RolePerMissionService;
import cn.ito.zjgsu.service.RoleService;
import cn.ito.zjgsu.service.UserService;
import cn.ito.zjgsu.utils.EncryptGenerator;

public class UserRealm extends AuthorizingRealm {
	
	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	@Resource
	private RolePerMissionService rolePerMissionService;
	
	@Autowired
	private EncryptGenerator encryptGenerator;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		String currentUsername = (String) super.getAvailablePrincipal(principals);
		UserExample userExample = new UserExample();
		userExample.or().andUsernameEqualTo(currentUsername);
		User user = userService.findUserByExample(userExample);

		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		if (user != null) {
			RoleExample roleExample = new RoleExample();
			roleExample.or().andRoleIdEqualTo(user.getRoleId());
			Role role = roleService.findRoleByExample(roleExample);
			simpleAuthorInfo.addRole(role.getRoleName());
			List<String> permissions = rolePerMissionService.findPermissionsByRoleid(role.getRoleId());
			simpleAuthorInfo.addStringPermissions(permissions);
			return simpleAuthorInfo;
		}

		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		UserExample userExample = new UserExample();
		userExample.or().andUsernameEqualTo(token.getUsername());
		User user = userService.findUserByExample(userExample);
		if (user != null) {

			if (user.getPassword().equals(encryptGenerator.encrypt(new String(token.getPassword()), user.getSalt()))) {
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(),
						this.getName());
				return authcInfo;
			} else {
				throw new IncorrectCredentialsException();
			}
		} else {
			throw new UnknownAccountException();
		}

	}

}